package com.huanghuai.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huanghuai.vo.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 认证成功处理器,认证成功就会调用该接口的方法
 */
@Component
@Slf4j
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private ObjectMapper objectMapper;  //对象序列化器，可以进行序列化和反序列化
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        HttpResult httpResult = HttpResult.builder()
                .code(1)
                .msg("登陆成功")
                .build();
        String strResponse = objectMapper.writeValueAsString(httpResult);
        response.setCharacterEncoding("UTF-8");//设置响应字符集
        response.setContentType("application/json;charset=utf-8");//设置响应内容类型
        PrintWriter writer = response.getWriter();//获取书写区
        writer.println(strResponse);
        writer.flush();


    }
}
